<script>
  import SubMenu from "./SubMenu.vue"
  import MenuItem from "./MenuItem.vue"
  import MenuHeader from "./MenuHeader.vue"

  export default {
    name: "Menu",
    render: function(createElement) {
      return createMenu(createElement, this.menuTreeData, this);
    },
    props:{
      menuTreeData: {
        type: Array,
        required:true
      }
    }
  }

  /**
   * 创建无限等级菜单
   * @param createElement  vue中的render参数
   * @param treeData       树结构数据
   * @param component      调用的组件，用于生成slot
   * @returns {*}          创建的元素
   */
  function createMenu(createElement, treeData, component) {
    //验证传入的参数是否合法
    // if(typeof(createElement) !== "function" || treeData.length === 0) return;
    //创建菜单标题
    let menuHeader = createElement(MenuHeader, {props:{header:"主菜单"}});
    //解析子菜单集合
    let subMenuElements = [];
    treeData.forEach(data=>subMenuElements.push(createSingleSubMenu(createElement, data)));
    //返回菜单，同时包含一个默认插槽进去：component.$slots.default
    return createElement("ul", {
      attrs: {
        class: "sidebar-menu"
      }
    },[menuHeader, ...subMenuElements, component.$slots.default]);
  }

  /**
   * 创建单个子菜单元素
   * @param createElement  vue的render参数
   * @param data           单条数据
   * @returns {*}          创建的原始s
   */
  function createSingleSubMenu(createElement, data) {
    //有子元素则创建子菜单，否则创建菜单条目
    if(data.children && data.children.length>0) {
      let childElements = [];
      data.children.forEach(c=>childElements.push(createSingleSubMenu(createElement, c)));
      return createElement(SubMenu, {
        props: {
          label: data.name,
          icon: data.icon?data.icon:"fa fa-circle-o",
        }
      }, childElements);
    } else {
      return createElement(MenuItem, {
        props:{
          url: data.url,
          label: data.name
        }
      })
    }
  }
</script>



// WEBPACK FOOTER //
// Menu.vue?5a01c958
